package com.budwk.app.sqfwV2.service.dayingRoad;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplateExcelCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuRedRecordPdfDTO;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuWhiteRecordPdfDTO;
import com.budwk.app.sqfwV2.enums.RedWhite;
import com.budwk.app.sqfwV2.enums.RedWhiteExcel;
import com.budwk.app.sqfwV2.generator.dayingRoadExcel.*;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.result.Result;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.Param;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@IocBean
public class DaYingLuRedWhiteRecordExcelService extends SqfwTemplateExcelCommonService {

    @Inject
    SysUserService sysUserService;
    @Inject
    SqfwFormsummaryNewService sqfwFormsummaryNewService;

    public List<GenerateExcelUrlVO> createExcel(List<ExcelCreateConfig> excelConfigList, String userId,
                                                List<String> sqfwIdList, String startTime, String endTime) {
        Sys_user sysUser = sysUserService.fetch(userId);

        // 设置一些基础的信息
        BaseExcelParamDTO baseExcelParam = new BaseExcelParamDTO();
        baseExcelParam.setDownloadDate(new Date());
        baseExcelParam.setCreateUserId(userId);
        baseExcelParam.setCreateUserName(sysUser.getUsername());
        baseExcelParam.setCreateUserSigUrl(sysUser.getSignatureUrl());
        baseExcelParam.setUnitId(sysUser.getUnitId());
        baseExcelParam.setUnitName(sysUser.getUnitName());

        List<Sqfw_formSummary_new> formSummaryList;

       if (excelConfigList.size() == 1) {
           Cnd cnd = Cnd.NEW();
           cnd.and(Sqfw_formSummary_new::getSqfwId, "in", sqfwIdList);
           if (StringUtils.isNotBlank(startTime)) {
               cnd.and(Sqfw_formSummary_new::getFillDate, ">=", startTime);
           }
           if (StringUtils.isNotBlank(endTime)) {
               cnd.and(Sqfw_formSummary_new::getFillDate, "<=", endTime + " 23:59:59");
           }
           formSummaryList = sqfwFormsummaryNewService.query(cnd);
       } else {
           formSummaryList = queryForSummaryData(sqfwIdList,null);
       }

        String ids = formSummaryList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.joining(""));
        List<SqfwExcelForSummaryBO> dataList = getFieldDataList(formSummaryList);
        customerPopularBaseExcelParam(baseExcelParam, userId, sqfwIdList);

        List<ExcelGeneratorConfig> generatorConfigList = getExcelCodeGeneratorConfig(excelConfigList, baseExcelParam);

        List<GenerateExcelUrlVO> resultList = Lists.newArrayList();
        for (ExcelGeneratorConfig generatorConfig : generatorConfigList) {
            BaseTemplateExcelGenerator generator = generatorConfig.getGenerator();
            // 1 检查是否已经下载过
            String title = String.format("%s%s", "下载", generator.getDownloadFileName());

            // 2 下载台账
            SqfwExcelCreateCommonBO sqfwExcelCreateCommonBO = new SqfwExcelCreateCommonBO();
            sqfwExcelCreateCommonBO.setBaseExcelParamDTO(baseExcelParam);
            sqfwExcelCreateCommonBO.setDataList(dataList);

            ExcelCreateConfig generateConfig = new ExcelCreateConfig();
            BeanUtil.copyProperties(generatorConfig.getExcelCreateConfig(),generateConfig);
            sqfwExcelCreateCommonBO.setExcelCreateConfig(generateConfig);

            GenerateExcelUrlVO excel = generator.createExcel(sqfwExcelCreateCommonBO);
            resultList.add(excel);

            // 3 记录下载日志
            CommonComponent.insertDownRecordLog(JSONObject.toJSONString(formSummaryList), JSONObject.toJSONString(Result.data(excel.getExcelUrl())),
                    title, excel.getExcelUrl(), ids);
        }
        return resultList;
    }


    /**
     * 允许自定义生成excel的原材料，
     *
     * @param baseExcelParam 生成excel提供的原材料
     * @param userId         用户id
     * @param sqfwIdList     社区服务id列表
     */
    @Override
    protected void customerPopularBaseExcelParam(BaseExcelParamDTO baseExcelParam, String userId, List<String> sqfwIdList) {
        Sys_user user = sysUserService.getUserById(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone", user.getMobile());
        baseExcelParam.setCustomerParamMap(map);
    }

    @Override
    protected void customerPopularBaseExcelParamForAdmin(BaseExcelParamDTO baseExcelParam, String userId, List<String> formSummaryNewIdList) {
        Sys_user user = sysUserService.getUserById(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone", user.getMobile());
        baseExcelParam.setCustomerParamMap(map);
    }


    /**
     * 选择使用哪一个excel生成器来生成excel，默认一个Excel会对应一个Generator
     *
     * @return 结果
     */
    @Override
    protected List<ExcelGeneratorConfig> getExcelCodeGeneratorConfig(List<ExcelCreateConfig> excelConfigList, BaseExcelParamDTO baseExcelParam) {
        List<ExcelGeneratorConfig> generatorList = Lists.newArrayList();
        // TODO 在这里通过baseExcelParam的属性excelGenerateConfigList作为条件添加你所需要生成excel的Generator

        for (ExcelCreateConfig config : excelConfigList) {
            if (RedWhiteExcel.WHITE_SELF_CATERING_STATISTICS.getCode().equals(config.getFileIdentity())) {
                ExcelGeneratorConfig excelGeneratorConfig = new ExcelGeneratorConfig();
                excelGeneratorConfig.setGenerator(new WhiteSelfCateringStatisticsExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(config);
                generatorList.add(excelGeneratorConfig);
            }
            if (RedWhiteExcel.WHITE_INFORMATION_STATISTICS.getCode().equals(config.getFileIdentity())) {
                ExcelGeneratorConfig excelGeneratorConfig = new ExcelGeneratorConfig();
                excelGeneratorConfig.setGenerator(new WhiteInformationStatisticsExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(config);
                generatorList.add(excelGeneratorConfig);
            }
            if (RedWhiteExcel.WHITE_TRACKING_REPORT.getCode().equals(config.getFileIdentity())) {
                ExcelGeneratorConfig excelGeneratorConfig = new ExcelGeneratorConfig();
                excelGeneratorConfig.setGenerator(new WhiteTrackingReportExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(config);
                generatorList.add(excelGeneratorConfig);
            }
            if (RedWhiteExcel.WHITE_WORK_PROMOTION.getCode().equals(config.getFileIdentity())) {
                ExcelGeneratorConfig excelGeneratorConfig = new ExcelGeneratorConfig();
                excelGeneratorConfig.setGenerator(new WhiteWorkPromotionExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(config);
                generatorList.add(excelGeneratorConfig);
            }
            if (RedWhiteExcel.RED_TRACKING_REPORT.getCode().equals(config.getFileIdentity())) {
                ExcelGeneratorConfig excelGeneratorConfig = new ExcelGeneratorConfig();
                excelGeneratorConfig.setGenerator(new RedTrackingReportExcelGenerator());
                excelGeneratorConfig.setExcelCreateConfig(config);
                generatorList.add(excelGeneratorConfig);
            }
        }

        return generatorList;
    }

    @Override
    protected AbstractCustomerPdfCreateField parseParamData(String paramDataStr) {
        DaYingLuWhiteRecordPdfDTO pdfDTO = JSONUtil.toBean(paramDataStr, DaYingLuWhiteRecordPdfDTO.class);
        String celebratoryEvents = pdfDTO.getCelebratoryEvents();
        if (RedWhite.RED.getName().equals(celebratoryEvents)) {
            return JSONObject.parseObject(paramDataStr, DaYingLuRedRecordPdfDTO.class);
        } else {
            return JSONObject.parseObject(paramDataStr, DaYingLuWhiteRecordPdfDTO.class);
        }
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link com.budwk.app.sqfw.constants.SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    protected String getSqfwFormSummaryType() {
        return SqfwFormSummaryConstants.red_white_record;
    }
}
